package netty.test

import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.bootstrap.Bootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import kotlin.system.exitProcess


object Client {
    //服务端的IP
    private val SERVER_HOST = "192.168.1.153"


    fun start(beginPort: Int, nPort: Int) {
        println("client starting....")
        val eventLoopGroup = NioEventLoopGroup()
        val bootstrap = Bootstrap()
        bootstrap.group(eventLoopGroup)
        bootstrap.channel(NioSocketChannel::class.java)
        bootstrap.option(ChannelOption.SO_REUSEADDR, true)
        bootstrap.handler(object : ChannelInitializer<SocketChannel>() {
            override fun initChannel(ch: SocketChannel) {}
        })

        var index = 0
        var port: Int
        //从10000的端口开始，按端口递增的方式进行连接
        while (!Thread.interrupted()) {
            port = beginPort + index
            try {
                val channelFuture = bootstrap.connect(SERVER_HOST, port)
                channelFuture.addListener { future ->
                    if (!future.isSuccess) {
                        println("connect failed, exit!")
                        exitProcess(0)
                    }
                }
                channelFuture.get()
            } catch (e: Exception) {
            }

            if (++index == nPort) {
                index = 0
            }
        }
    }
}